package flc.ast.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;

import java.util.List;

import flc.ast.AppConfig;
import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.DeviceAdapter;
import flc.ast.databinding.ActivitySearchDeviceBinding;
import flc.ast.utils.Content;

public class SearchDeviceActivity extends BaseAc<ActivitySearchDeviceBinding> {

    private CastScreenManager mCastScreenManager;
    private boolean isSearch = false;
    private DeviceAdapter deviceAdapter;
    private int oldPosition;


    @Override
    protected int onCreate() {
        return R.layout.activity_search_device;
    }

    @Override
    protected void initView() {
        mDataBinding.ivSearchBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.rvDeviceList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        deviceAdapter = new DeviceAdapter();
        mDataBinding.rvDeviceList.setAdapter(deviceAdapter);
        deviceAdapter.addChildClickViewIds(R.id.ivDeviceItemSel);
        deviceAdapter.setOnItemChildClickListener(this);

        //注册投屏
        registerScreen();
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (view.getId() == R.id.ivDeviceItemSel) {
            if (deviceAdapter.getItem(position).isConnect()) {
                Content.IsConnect = false;
                deviceAdapter.getItem(position).setConnect(false);
                deviceAdapter.notifyDataSetChanged();
                mCastScreenManager.disConnect();
                Content.ConnectName = "";
            } else {
                Content.IsConnect = true;
                deviceAdapter.getItem(oldPosition).setConnect(false);
                oldPosition = position;
                deviceAdapter.getItem(position).setConnect(true);
                deviceAdapter.notifyDataSetChanged();
                mCastScreenManager.connect(deviceAdapter.getItem(position));
                Content.ConnectName = deviceAdapter.getItem(position).getName();
            }
        }
    }

    @Override
    protected void initData() {

    }

    //注册投屏
    private void registerScreen() {
        CastScreenManager.init(AppConfig.TEST_APP_ID, AppConfig.TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {
            @Override
            public void onInit(boolean success) {
                dismissDialog();
                ToastUtils.showLong(success ? getString(R.string.init_suc) : getString(R.string.init_def));
                if (success) {
                    Content.IsInit = true;
                    isSearch = true;
                    showDialog(getString(R.string.search_ing));
                    mCastScreenManager.startBrowse();
                } else {
                    Content.IsInit = false;
                }
            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                dismissDialog();
                isSearch = false;
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (deviceAdapter != null) {
                        mDataBinding.llDeviceNoData.setVisibility(View.GONE);
                        mDataBinding.rvDeviceList.setVisibility(View.VISIBLE);
                        deviceAdapter.setList(list);
                        //回显连接状态
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(Content.ConnectName)) {
                                list.get(i).setConnect(true);
                            }
                        }
                        deviceAdapter.notifyDataSetChanged();
                    } else {
                        mDataBinding.llDeviceNoData.setVisibility(View.VISIBLE);
                        mDataBinding.rvDeviceList.setVisibility(View.GONE);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showLong(R.string.search_over);
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showLong(R.string.auth_def);
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = getString(R.string.no_agreement);
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = getString(R.string.lelian_agreement);
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = getString(R.string.dlna_agreement);
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = getString(R.string.im_agreement);
                        break;
                }
                if (lelinkServiceInfo.getName() != null && !TextUtils.isEmpty(lelinkServiceInfo.getName())) {
                    Content.IsConnect = true;
                    Content.ConnectName = lelinkServiceInfo.getName();
                } else {
                    Content.IsConnect = false;
                    Content.ConnectName = "";
                }
                ToastUtils.showLong(getString(R.string.conn_device) + lelinkServiceInfo.getName() + getString(R.string.agreement_to) + strProtocol);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                Content.IsConnect = false;
                String text = getString(R.string.break_device) + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + getString(R.string.wait_right);
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_refuse);
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + getString(R.string.saorao_request_over);
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + getString(R.string.black_list);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_break);
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + getString(R.string.no_online);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_def);
                            break;
                    }
                }
                ToastUtils.showLong(text);
            }
        });
        if (!Content.IsInit) {
            showDialog(getString(R.string.init_ing));
            mCastScreenManager.init();
        }
    }

}